package com.jing.shop.domain.exception;

import com.jing.shop.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler2 {

    @ExceptionHandler
    @ResponseBody
    public Result<String> handle(ServiceException se){
        log.error("业务异常"+se);
        return Result.error(se.getCode(),se.getMessage());
    }

    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<Result<String>> handleValidatedExceptio(Exception e){
        Result<String> result=null;
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex=(MethodArgumentNotValidException) e;
            String errorMessages=ex.getBindingResult().getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining(";"));
            result=Result.error(HttpStatus.BAD_REQUEST.value(),errorMessages);
         } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex=(ConstraintViolationException) e;
            String errorMessages=ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining(";"));
            result=Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        } else if (e instanceof BindException) {
            BindException ex=(BindException) e;
            String errorMessages=ex.getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage)
                    .collect(Collectors.joining(";"));
            result=Result.error(HttpStatus.BAD_REQUEST.value(), errorMessages);
        }
        return new ResponseEntity<>(result,HttpStatus.BAD_REQUEST);
    }











}
